<?php


namespace app\admin\controller;


use app\BaseController;
use app\middleware\admin\Auth;
use app\model\Product as ProductModel;
use think\facade\Db;

class Product extends BaseController
{
    protected $middleware=[Auth::class];
    public function index()
    {
        $keyword=request()->param('keyword');

        $data=ProductModel::when($keyword,function ($query) use($keyword){
            $query->where('name','like',"%{$keyword}%");
        })->with('cate')
        ->order('id','desc')->paginate(10);

        return $this->success($data);
    }


    public function create()
    {
        return $this->success(ProductModel::create(request()->param()));
    }


    public function update($id)
    {
        $params=request()->param();

        if (!empty($params['num']) && $params['num']>0) {
            $str = $params['name'].'的庫存加'.$params['num'];
        } else {
            $str = $params['name'].'的庫存減'.$params['num'];
        }

        Db::table('admin_log')->insert([
            'type'=>1,
            'admin_id'=>request()->userid,
            'content'=>$str,
            'created_at'=>time()
        ]);
        return $this->success(ProductModel::where('id',$id)->update($params));
    }


    public function delete($id)
    {
        return $this->success(ProductModel::where('id',$id)->delete());
    }
}